package procilege.impl.formatter;

import java.util.Iterator;

import org.apache.solr.util.OpenBitSet;

import merisis.util.BitUtil;

import procilege.compute.ExprFormatTraveller;
import procilege.compute.PlaceTypeMetadata;
import procilege.compute.PlaceType;
import procilege.lang.Name;
import procilege.lang.PrivExprElement;
import procilege.lang.PrivExprMergence;

@PlaceTypeMetadata(type = PrivExprMergence.class)
public class PrivExprMergenceFormatter implements
		PlaceType<ExprFormatTraveller> {

	public void visit(ExprFormatTraveller tr, Object place) {

		StringBuilder sb = tr.getBuilder();
		PrivExprMergence n = (PrivExprMergence) place;

		boolean isNotFirstElem = false;
		sb.append('(');
		if (!n.getPrivileges().isEmpty()) {

			Iterator<PrivExprElement> itr = n.getPrivileges().iterator();
			PrivExprElement t = itr.next();
			tr.setout(t);
			if (!isNotFirstElem)
				isNotFirstElem = true;

			while (itr.hasNext()) {

				t = itr.next();
				sb.append("*");
				tr.setout(t);
			}
		}

		if (n.getEntityExpr() != null) {
			sb.append('/');
			sb.append('(');
			tr.setout(n.getEntityExpr());
			sb.append(')');
		}

		if (n.getRestrictionExpr() != null) {

			if (isNotFirstElem)
				sb.append('*');

			sb.append('[');
			tr.setout(n.getRestrictionExpr());
			sb.append(']');
		}

		OpenBitSet bn = n.getBoundNames();
		if (!bn.isEmpty()) {
			sb.append('<');
			BitUtil.format(sb, n.getBoundNames(), ",");
			sb.append('>');
		}

		sb.append(')');
	}
}